#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>
#include <linux/poll.h>

static struct fasync_struct *button_async;

static unsigned int keyval;

typedef struct pin_desc{
	unsigned int keyval;
	unsigned int pin;
};

struct pin_desc pins_desc[4] = {
	{S3C2410_GPF0, 0x01},
	{S3C2410_GPF2, 0x02},
	{S3C2410_GPG3, 0x03},
	{S3C2410_GPG11, 0x04},
};

static struct class *fifth_class;
static struct class_device *fifth_class_device;

static irqreturn_t button_irq(int irq, void *dev_id)
{
	struct pin_desc *pindesc = (struct pin_desc *)dev_id;
	unsigned int retval;

	retval = s3c2410_gpio_getpin(pins_desc->pin);
	if(retval)
	{
		keyval = 0x80 | pindesc->keyval;
	}
	else
	{
		keyval = pindesc->keyval;
	}
	kill_fasync(&button_async, SIGIO, POLL_IN);
	
	return IRQ_HANDLED;
}

static int fifth_drv_open(struct inode *inode, struct file *file)
{
	request_irq(IRQ_EINT0, button_irq, IRQT_BOTHEDGE, "S2", &pins_desc[0]);
	request_irq(IRQ_EINT2, button_irq, IRQT_BOTHEDGE, "S3", &pins_desc[1]);
	request_irq(IRQ_EINT11, button_irq, IRQT_BOTHEDGE, "S4", &pins_desc[2]);
	request_irq(IRQ_EINT19, button_irq, IRQT_BOTHEDGE, "S5", &pins_desc[3]);
	return 0;
}

ssize_t fifth_drv_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
{
	if(size != 1)
		return -EINVAL;

	copy_to_user(buf, &keyval, 1);

	return 1;
}

static int fifth_drv_close(struct inode *inode, struct file *file)
{
	free_irq(IRQ_EINT0, &pins_desc[0]);
	free_irq(IRQ_EINT2, &pins_desc[1]);
	free_irq(IRQ_EINT11, &pins_desc[2]);
	free_irq(IRQ_EINT19, &pins_desc[3]);
	return 0;
}

static int fifth_drv_fasync (int fd, struct file *filp, int on)
{
	printk("fifth_drv_fasync\n\r");
	return fasync_helper(fd, filp, on, &button_async);
}

static struct file_operations fifth_drv_fops = {
	.owner   = THIS_MODULE,
	.open    = fifth_drv_open,
	.read    = fifth_drv_read,
	.release = fifth_drv_close,
	.fasync  = fifth_drv_fasync,
};

int major;
static int fifth_drv_init(void)
{
	major = register_chrdev(0, "fifth_drv", &fifth_drv_fops);

	fifth_class = class_create(THIS_MODULE, "fifth_drv");

	fifth_class_device = class_device_create(fifth_class, NULL, MKDEV(major, 0), NULL, "fifth_drv");
}

static void fifth_drv_exit(void)
{
	unregister_chrdev(major, "fifth_drv");
	class_device_unregister(fifth_class_device);
	class_destroy(fifth_class);
}

module_init(fifth_drv_init);
module_exit(fifth_drv_exit);

MODULE_LICENSE("GPL");


